%%Test Program for Strang RC Circuit


%% Reference Material
% http://cns.bu.edu/~eric/readings/strang.pdf

%% Circuit Diagram
% http://cns.bu.edu/~eric/readings/RC.jpg

%%  Variables
% The following matrixes and vectors are needed
%
% Sparse matrixes are used throughout the code
%
% * A Incidence matrix  node by edge
% * A_0 Reduced incidence matrix nodes by edge-1
% * b Voltage source vector b edge by 1
% * f Current source vector node by 1
% * G Conductance matrix G edge by edge
% * C Capacitance matrix edge by edge
% * y Current vector  node by 1
% * x Potentials node by 1
% * e Potential differences edge by 1

%% Kirchoff KCL and KVL
% KCL and KVL may be succinctly stated in matrix vector form as  follows.
%
% Ohms law (constitutive) appears below in conductance form: 

%% Ohms Law
% $$y_r=Ge$$
%

%% A capacitive constituitive law
%%
%
% $$y_c=\mbox{-}C\dot{e}~=~\mbox{-}C\frac{d}{dt}(b~\mbox{-}A_0 x)~=~ CA_0\dot{x}$$
%

%% A capacitance matrix C allows reactive circuits to be handled.
%
% The ohmic current, together with the displacement (capacitive) current, simply
% balances the current sources:
%%
%%
%
% $$A_0^tG(b~ \mbox{-}~A_0x) \mbox{-}A_0^t CA_0\dot{x} ~=~ f$$
%
%% SUMMARY OF KCL/KVL/OHM

%% Edge voltage drops
% $$e=b~ \mbox{-}~ A_0x$$

%% Capacitive (displacement current) 
%
% $$y_c~=\mbox{-}~C\dot{e}=CA_0\dot{x}$$ 

%% Ohm's Law
% $$y_r=Ge$$

%% KCL
%
% $$A_0^ty=f$$

%% KCL/KVL with only resistive edge variables according to Strang
%%
% $$A_0^tG(b~\mbox{-}~A_0x)=f$$
%

%% KCL/KVL with resistive and capacitive  elements according to ELS
%%
%
% $$A_0^tG(b~\mbox{-}~A_0x)\mbox{-}A_0^t CA_0\dot{x} ~=~ f$$

% ELS 11/1/2006




%%Incidence matrix
% A= -1 1;1 -1
% A_0= [-1 1]^t
i=[];j=[];s=[]; %initialize to empty
%
i=[i 1]; j=[j 1]; s=[s -1];
i=[i 1]; j=[j 2]; s=[s 1];
i=[i 2]; j=[j 1]; s=[s 1];
i=[i 2]; j=[j 2]; s=[s -1];
A=sparse(i,j,s);
%
%% Reduced incidence matrix: chop last column
A_0=A(:,1); % chop last column to form reduced Incidence matrix
%
%% Conductivity matrix and Capacitance Matrix
R1=10; %10 Ohms
R2=5; %5 Ohms
C=.01; %.01 Farad
G=[1/R1 0;0 0];
C=[0 0; 0 C];
G=sparse(G);
C=sparse(C);
%% Voltage sources
%Battery V_0 pos up
%two Resistors R_1=10 and R_2=5
%
V_0=10; % 10 volt source
b=[-V_0;0]; % b is a column vector
b=sparse(b);
%% Solve

%%
%
% $$A_0^t G (b~\mbox{-}~A_0x) \mbox{-} A^tCA_0\dot{x}~=~f ~=~ 0$$
% 

%%
% $$\dot{x}={(A_0^t C A_0)}^{\mbox{-1}} A_0^tG(b~\mbox{-}~A_0x)$$
%

x=zeros(100,1);
t=zeros(100,1);
x(1)=0; t(1)=0;
delt=0.01;
for j=2:length(x)
x(j)=x(j-1)+delt*A_0'*G*(b-A_0*x(j-1))/(A_0'*C*A_0);
t(j)=t(j-1)+delt;
end
figure,plot(t,x); title('RC\_Strang'); axis([0 1 0 10]);ylabel('Volts');xlabel('Time-Secs');
